<?php
namespace app\admin\controller;

use think\Db;
use think\Loader;
use think\Request;

class Category extends Admin
{
    /*
     * 文章分类列表页
     * */
    public function Index()
    {
        $list=model('Category')->getCategory();
        $this->assign('list',$list);
        return $this->fetch('category_list');
    }
    /*
     * 添加分类
     * */
    public function CategoryAdd(){
        if(Request::instance()->isPost()){
            $data=input('post.');
            $validate=Loader::validate('Category');
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            if(model('Category')->addCate($data)){
                $this->success('操作成功!',url('Category/Index'));
            }else{
                $this->error('操作失败!');
            }
        }
        $data['pid']=input('pid','','intval');
        $data['list']=model('Category')->getCategory(array('status'=>'1'));
        $this->assign($data);
        return $this->fetch('category_add');
    }
    /*
     * 编辑分类
     * */
    public function CategoryEdit(){
        if(Request::instance()->isPost()){
            $data=input('post.');
            $data['status']=isset($data['status'])?$data['status']:0;
            $validate=Loader::validate('Category');
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            if(model('Category')->modCate($data)){
                $this->success('操作成功!',url('Category/CategoryEdit',array('id'=>$data['id'])));
            }else{
                $this->error('操作失败!');
            }
        }
        $id=input('id','','intval');
        $data['row']=model('Category')->where('id',$id)->find();
        if(!$data['row']){
            $this->error('操作有误');
        }
        $data['list']=model('Category')->getCategory();
        $this->assign($data);
        return $this->fetch('category_edit');
    }
    /*
     * 删除分类
     * */
    public function CategoryDel(){
        $id=input('post.id','','intval');
        if(!$id){
            $this->error('操作有误');
        }
        if (Db::name('Category')->where('pid', $id)->find()) {
            $this->error('删除失败，请先删除子分类');
        }
        $flag = model('Category')->delCate($id);
        if ($flag) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }
}
